package com.power.listener;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.power.mapper.TClueMapper;
import com.power.model.TClue;
import com.power.model.TUser;
import com.power.util.LoginInfoUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

@Slf4j
public class TClueUploadExcelDataListener implements ReadListener<TClue> {
    private TClueMapper tClueMapper;
    private TUser tUser;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<TClue> tClueDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public TClueUploadExcelDataListener(TClueMapper tClueMapper, String token) {
        this.tClueMapper = tClueMapper;
        this.tUser = LoginInfoUtil.getUserFromToken(token);
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param tClue   one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(TClue tClue, AnalysisContext context) {
        tClue.setCreateBy(tUser.getId());
        tClue.setCreateTime(new Date());
        log.info("解析到一条数据:{}", JSONUtil.toJsonStr(tClue));
        tClueDataList.add(tClue);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (tClueDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            tClueDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", tClueDataList.size());
        tClueMapper.saveExcelData(tClueDataList);
        log.info("存储数据库成功！");
    }
}
